angular.module('U9ImHd.services')

.factory('AppManager', ['$q', '$cordovaZip', '$cordovaFile', 'Http', 'Config', 'Help', 'APPCONSTANTS',
    function($q, $cordovaZip, $cordovaFile, Http, Config, Help, APPCONSTANTS) {
        var amDefer = $q.defer(),
            _appList = null,
            _apps = [],
            o = {
                loaded: amDefer.promise
            };

        o.getApps = function () {
            var results = [];
            angular.forEach(angular.copy(_apps), function (app) {
                app.DisplayImage = Help.getFullPath(app.DisplayImage, app.AppID);
                if (app.MouseDownImage) {
                    app.MouseDownImage = Help.getFullPath(app.MouseDownImage, app.AppID);
                }
                results.push(app);
            });
            return results;
        };

        init();

        return o;

        function init () {
            Config.loaded.finally(function () {
                _apps = Config.get('apps');
                amDefer.resolve();
                //downloadApp('QualityJudge', "5be4e1785966efd423746524124edd2f.zip");
                //getAppList();
            });
        }

        function getAppList () {
            var defer = $q.defer();

            Http.post({
                url: APPCONSTANTS.getAppsURL,
                source: 1
            }).then(function (data) {
                _appList = data;
                defer.resolve(data);
            }, function () {
                defer.reject();
            });

            return defer.promise;
        }

        function installApp (appID, fileName) {
            var defer = $q.defer();

            downloadApp(appID, fileName).then(function () {
                return $cordovaFile.readAsText(Help.getAppsDir() + appID, APPCONSTANTS.appConfigFileName);
            }).then(function (data) {
                _apps.push(angular.fromJson(data));
                return Config.set('apps', _apps);
            }).then(function () {
                defer.resolve();
            }).catch(function () {
                defer.reject();
            });

            return defer.promise;
        }

        function unInstallApp (appID) {
            var defer = $q.defer();

            var index = checkInstalled(appID);
            if (index === -1) {
                defer.resolve();
            } else {
                removeApp(appID).then(function () {
                    _apps.splice(index, 1);
                    return Config.set('apps', _apps); 
                }).then(function () {
                    defer.resolve();
                }).catch(function () {
                    defer.reject();
                });
            }

            return defer.promise;
        }

        function checkInstalled (appID) {
            var len = _apps.length;
            for (var i = 0; i < len; i++) {
                if (_apps[i].appID === appID) {
                    break;
                }
            }
            if (i === len) {
                return -1;
            } else {
                return i; 
            }
        }

        function downloadApp (appID, fileName) {
            var defer = $q.defer();

            Http.post({
                url: APPCONSTANTS.downloadAppURL,
                data: {
                    Parameter: {
                        FileName: fileName
                    }
                },
                responseType: 'arraybuffer',
                source: 1
            }).then(function (result) {
                if (window.cordova) {
                    var blob = new Blob([result.data], { type: "application/octet-binary" });
                    return $cordovaFile.writeFile(Help.getConfigDir(), appID + '.zip', blob, true);
                } else {
                    return $q.reject();
                }
            }).then(function () {
                var fileURL = Help.getConfigDir() + appID + '.zip';
                return $cordovaZip.unzip(fileURL, Help.getAppsDir());
            }).then(function () {
                return $cordovaFile.removeFile(Help.getConfigDir(), appID + '.zip');
            }).then(function () {
                defer.resolve();
            }).catch(function () {
                defer.reject();
            });

            return defer.promise;
        }

        function removeApp (appID) {
            var defer = $q.defer();

            if (window.cordova) {
                $cordovaFile.removeRecursively(Help.getAppsDir(), appID).then(function () {
                    defer.resolve();
                }, function (error) {
                    defer.reject();
                });
            } else {
                defer.reject();
            }

            return defer.promise;
        }
    }
]);